package com.wl.user.login.controller;

import com.wl.bean.Result;
import com.wl.entity.Follow;
import com.wl.user.login.biz.IFollowBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/follow")
public class FollowController {

    @Autowired
    private IFollowBiz followBiz;

    //关注用户
    @PostMapping("/add")
    public Result follow(@RequestBody Follow followRequest){
        if(followRequest.getFollowerId().equals(followRequest.getFollowingId())) {
            return new Result(0, "不能关注自己", null);
        }
        followBiz.insertOrUpdateFollow(followRequest);
        return new Result(1,"关注成功",null);
    }

    //获取用户关注数和粉丝数
    @GetMapping("/stats/{userId}")
    public Map<String, Long> countFollowStats(@PathVariable Integer userId) {
        Map<String, Long> status = followBiz.countFollowStats(userId, userId);

        // 打印查询结果，调试用
        System.out.println("Raw query result: " + status);

        Map<String, Long> result = new HashMap<>();
        result.put("followingCount", status.getOrDefault("following_count", 0L));
        result.put("followerCount", status.getOrDefault("follower_count", 0L));
        return result;
    }

    // 取消关注
    @DeleteMapping("/{followerId}/{followingId}")
    public Result unfollow(
            @PathVariable Integer followerId,
            @PathVariable Integer followingId,
            @RequestParam(defaultValue = "0") Integer status) throws Exception {  // 添加@RequestParam注解

        if (followerId == null || followingId == null) {
            throw new IllegalArgumentException("followerId和followingId不能为null");
        }
        // status现在有默认值0，可以不用检查null
        followBiz.updateStatus(followerId, followingId, status);
        return new Result(1, "已取消关注", null);
    }

    //检查关注状态
    @GetMapping("/status/{followerId}/{followingId}")
    public boolean checkFollower(@PathVariable Integer followerId, @PathVariable Integer followingId){
        boolean isFollowing = followBiz.existsFollowRelation(followerId,followingId);
        return isFollowing;
    }
}
